from django.core.validators import FileExtensionValidator
from rest_framework import serializers

from apps.oaauth.middlewares import OAUser


class AddStaffSerializer(serializers.Serializer):
    realname = serializers.CharField(max_length=20, error_messages={"required": "请输入用户名"})
    email = serializers.EmailField(error_messages={"required": "请输入邮箱", "invalid": "请输入正确的邮箱格式!"})
    password = serializers.CharField(max_length=20, error_messages={"required": "请输入密码"})

    def validate(self, attrs):
        request = self.context.get('request')
        email = attrs.get('email')
        # 验证邮箱是否存在
        if OAUser.objects.filter(email=email).exists():
            raise serializers.ValidationError("邮箱已存在!")

        # 验证用户权限级别
        if request.user.department.leader.uid != request.user.uid:
            raise serializers.ValidationError("非部门领导不能添加员工!")
        return attrs


class ActiveStaffSerializer(serializers.Serializer):
    email = serializers.EmailField(error_messages={"required": "请输入邮箱", "invalid": "请输入正确的邮箱格式!"})
    password = serializers.CharField(max_length=20, error_messages={"required": "请输入密码"})
    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        user =  OAUser.objects.filter(email=email).first()

        print(user, user.check_password(password))
        if not user or not user.check_password(password):
            raise serializers.ValidationError('邮箱或密码错误!')
        attrs['user'] = user
        return attrs

class StaffUploadSerializer(serializers.Serializer):
    file = serializers.FileField(
        validators=[FileExtensionValidator(['xlsx', 'xls'])],
        error_messages={'required': '请上传文件！'}
    )



